import { Module } from 'vuex'

import {
  accountLoginRequest,
  requestUserInfoById,
  requestUserMenuByRoleId
} from '@/service/login/login'
import localCache from '@/utils/cache'
import { mapMenusToRoutes, mapMenusToPermissions } from '@/utils/map-menus'

import { IAccount } from '@/service/login/types'
import router from '@/router'

import { ILoginState } from './types'
import { IRootState } from '../types'

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: [],
      permissions: []
    }
  },
  getters: {},
  mutations: {
    changeToken(state, token: string) {
      state.token = token ?? ''
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    changeUserMenus(state, userMenus: any) {
      state.userMenus = userMenus

      //  根绝返回的数据type=2，来动态生成路由
      //userMenus --> routes
      const routes = mapMenusToRoutes(userMenus)
      // console.log(routes)
      routes.forEach((route) => {
        router.addRoute('main', route)
      })

      // 获取用户的按钮权限
      const permission = mapMenusToPermissions(userMenus)
      // console.log(permission)
      state.permissions = permission
    }
  },
  actions: {
    async accountLoginAction({ commit, dispatch }, payload: IAccount) {
      // console.log('登陆模块的vuex网络请求', payload)
      // 实现登陆逻辑
      // const loginResult = await accountLoginRequest(payload)
      // console.log(loginResult.data)
      // const { id, token } = loginResult.data
      // commit('changeToken', token)
      // localCache.setCache('token', token)

      const loginResult = await accountLoginRequest(payload)
      // console.log(loginResult)
      if (loginResult.code === 1) {
        return
      }
      const { id, token } = loginResult.data
      commit('changeToken', token)
      localCache.setCache('token', token)
      // 发送初始化的请求（完整的role/department）
      dispatch('getInitialDataAction', null, { root: true })

      // 根据id获取用户信息
      const userInfoResult = await requestUserInfoById(id)
      // console.log(userInfoResult)
      const userInfo = userInfoResult.data
      commit('changeUserInfo', userInfo)
      localCache.setCache('userInfo', userInfo)

      // 根据id获取用户的权限菜单
      const userMenusResult = await requestUserMenuByRoleId(userInfo.role.id)
      const userMenus = userMenusResult.data
      // console.log(userMenus)
      commit('changeUserMenus', userMenus)
      localCache.setCache('userMenus', userMenus)

      // 获取到数据之后，进行路由跳转
      router.push('/main')
    },
    loadLoaclLogin({ commit, dispatch }) {
      const token = localCache.getCache('token')
      if (token) {
        commit('changeToken', token)
        // 发送初始化的请求（完整的role/department）
        dispatch('getInitialDataAction', null, { root: true })
      }
      const userInfo = localCache.getCache('userInfo')
      if (userInfo) {
        commit('changeUserInfo', userInfo)
      }
      const userMenus = localCache.getCache('userMenus')
      if (userMenus) {
        commit('changeUserMenus', userMenus)
      }
    }
    // registerAction({ commit }, payload: any) {
    //   console.log('注册模块的vuex网络请求')
    // }
  }
}

export default loginModule
